package com.xteam.xnetworkdisk.utils;

import com.xteam.xnetworkdisk.utilsinterface.IPUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;

public class IPApiUtils implements IPUtils {


    private static final String API_URL = "http://ip-api.com/json/";


    public String getClientIpAddress(HttpServletRequest request) {
        Enumeration<String> headers = request.getHeaderNames();

        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.isEmpty()) {
            ipAddress = request.getHeader("X-Real-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty()) {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress;
    }


    public String getLocationByIp(String ip) throws Exception {
        String apiUrl = API_URL + ip;
        URL url = new URL(apiUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            return response.toString();
        }
    }

    @Override
    public String getDeviceDetails(HttpServletRequest request) {
        // 获取 User-Agent 信息
        String userAgent = request.getHeader("User-Agent");
        if (userAgent == null) {
            return "Unknown Device";
        }

        String deviceDetails = "Unknown Device";
        if (userAgent.contains("Windows")) {
            deviceDetails = "Windows";
        } else if (userAgent.contains("Mac")) {
            deviceDetails = "Mac";
        } else if (userAgent.contains("X11")) {
            deviceDetails = "Unix";
        } else if (userAgent.contains("Android")) {
            deviceDetails = "Android";
        } else if (userAgent.contains("iPhone")) {
            deviceDetails = "iPhone";
        } else if (userAgent.contains("iPad")) {
            deviceDetails = "iPad";
        }

        // 解析更多信息（浏览器、版本等）可以继续扩展

        return deviceDetails + " - " + userAgent;
    }

}
